apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
  name: d8allowprivilegeescalation
  labels:
    heritage: deckhouse
    module: admission-policy-engine
    security.deckhouse.io: security-policy
  annotations:
    metadata.gatekeeper.sh/title: "Allow Privilege Escalation in Container"
    description: >-
      Controls restricting escalation to root privileges. Corresponds to the
      `allowPrivilegeEscalation` field in a PodSecurityPolicy. For more
      information, see https://kubernetes.io/docs/concepts/security/pod-security-standards/
spec:
  crd:
    spec:
      names:
        kind: D8AllowPrivilegeEscalation
      validation:
        openAPIV3Schema:
          type: object
          description: >-
            Controls restricting escalation to root privileges. Corresponds to the
            `allowPrivilegeEscalation` field in a PodSecurityPolicy. For more
            information, see https://kubernetes.io/docs/concepts/security/pod-security-standards/
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package d8.pod_security_policies

        violation[{"msg": msg, "details": {}}] {
            c := input_containers[_]
            input_allow_privilege_escalation(c)
            msg := sprintf("Privilege escalation container is not allowed: %v", [c.name])
        }

        input_allow_privilege_escalation(c) {
            not has_field(c, "securityContext")
        }
        input_allow_privilege_escalation(c) {
            not c.securityContext.allowPrivilegeEscalation == false
        }
        input_containers[c] {
            c := input.review.object.spec.containers[_]
        }
        input_containers[c] {
            c := input.review.object.spec.initContainers[_]
        }
        input_containers[c] {
            c := input.review.object.spec.ephemeralContainers[_]
        }
        # has_field returns whether an object has a field
        has_field(object, field) = true {
            object[field]
        }
